'use client';

import { useRef, useState } from 'react';
import { Button, message, Modal, Tag, Space } from 'antd';
import { EyeOutlined, EditOutlined } from '@ant-design/icons';
import type { ProColumns, ActionType } from '@ant-design/pro-components';
import { ProTable, ProForm, ProFormSelect, ProFormTextArea } from '@ant-design/pro-components';
import { getSubmissionList, updateSubmission } from '@/apis/admin/submission';
import { Submission, SubmissionStatus, SubmissionStatusMap, SubmissionCategoryMap, UpdateSubmissionRequest } from '@/types/submission';

const SubmissionListPage = () => {
  const actionRef = useRef<ActionType>(null);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [editingSubmission, setEditingSubmission] = useState<Submission | null>(null);
  const [detailModalVisible, setDetailModalVisible] = useState(false);
  const [detailSubmission, setDetailSubmission] = useState<Submission | null>(null);

  const handleUpdate = async (values: any) => {
    if (!editingSubmission) return false;
    
    try {
      const params: UpdateSubmissionRequest = {
        id: editingSubmission.id,
        status: values.status,
        remark: values.remark,
      };
      await updateSubmission(params);
      message.success('更新成功');
      actionRef.current?.reload();
      return true;
    } catch (error) {
      message.error('更新失败');
      return false;
    }
  };

  const getStatusColor = (status: number) => {
    switch (status) {
      case SubmissionStatus.PENDING:
        return 'orange';
      case SubmissionStatus.APPROVED:
        return 'green';
      case SubmissionStatus.REJECTED:
        return 'red';
      default:
        return 'default';
    }
  };

  const columns: ProColumns<Submission>[] = [
    { 
      title: 'ID', 
      dataIndex: 'id', 
      key: 'id', 
      width: 200,
      hideInSearch: true,
      ellipsis: true,
    },
    { 
      title: '网站名称', 
      dataIndex: 'siteName', 
      key: 'siteName',
      width: 150,
    },
    { 
      title: '网站地址', 
      dataIndex: 'siteUrl', 
      key: 'siteUrl',
      width: 200,
      hideInSearch: true,
      render: (_, record) => (
        <a href={record.siteUrl} target="_blank" rel="noopener noreferrer" className="text-blue-500 hover:underline">
          {record.siteUrl}
        </a>
      ),
    },
    {
      title: '分类',
      dataIndex: 'category',
      key: 'category',
      width: 120,
      valueEnum: Object.entries(SubmissionCategoryMap).reduce((acc, [key, value]) => {
        acc[key] = { text: value };
        return acc;
      }, {} as Record<string, { text: string }>),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      valueEnum: {
        [SubmissionStatus.PENDING]: { text: SubmissionStatusMap[SubmissionStatus.PENDING] },
        [SubmissionStatus.APPROVED]: { text: SubmissionStatusMap[SubmissionStatus.APPROVED] },
        [SubmissionStatus.REJECTED]: { text: SubmissionStatusMap[SubmissionStatus.REJECTED] },
      },
      render: (_, record) => (
        <Tag color={getStatusColor(record.status)}>
          {SubmissionStatusMap[record.status as keyof typeof SubmissionStatusMap]}
        </Tag>
      ),
    },
    { 
      title: '联系邮箱', 
      dataIndex: 'email', 
      key: 'email',
      width: 180,
    },
    { 
      title: '提交时间', 
      dataIndex: 'createdAt', 
      key: 'createdAt', 
      valueType: 'dateTime', 
      hideInSearch: true,
      width: 160,
    },
    {
      title: '操作',
      key: 'action',
      hideInSearch: true,
      width: 150,
      render: (_, record) => (
        <Space>
          <Button
            type="text"
            icon={<EyeOutlined />}
            onClick={() => {
              setDetailSubmission(record);
              setDetailModalVisible(true);
            }}
          >
            查看
          </Button>
          <Button
            type="text"
            icon={<EditOutlined />}
            onClick={() => {
              setEditingSubmission(record);
              setIsModalVisible(true);
            }}
          >
            审核
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <>
      <ProTable<Submission>
        columns={columns}
        actionRef={actionRef}
        request={async (params) => {
          const res = await getSubmissionList({
            page: params.current,
            pageSize: params.pageSize,
            siteName: params.siteName,
            category: params.category,
            status: params.status,
            email: params.email,
          });
          return {
            data: res.data,
            total: res.total,
            success: true,
          };
        }}
        rowKey="id"
        search={{ labelWidth: 120 }}
        pagination={{
          defaultPageSize: 10,
          showSizeChanger: true,
        }}
        scroll={{ x: 1200 }}
      />

      {/* 审核模态框 */}
      <Modal
        title="审核提交"
        open={isModalVisible}
        onCancel={() => setIsModalVisible(false)}
        footer={null}
        destroyOnClose
      >
        <ProForm
          initialValues={{
            status: editingSubmission?.status,
            remark: editingSubmission?.remark,
          }}
          onFinish={async (values) => {
            const success = await handleUpdate(values);
            if (success) {
              setIsModalVisible(false);
            }
            return success;
          }}
        >
          <ProFormSelect
            name="status"
            label="审核状态"
            rules={[{ required: true, message: '请选择审核状态' }]}
            options={[
              { label: SubmissionStatusMap[SubmissionStatus.PENDING], value: SubmissionStatus.PENDING },
              { label: SubmissionStatusMap[SubmissionStatus.APPROVED], value: SubmissionStatus.APPROVED },
              { label: SubmissionStatusMap[SubmissionStatus.REJECTED], value: SubmissionStatus.REJECTED },
            ]}
          />
          <ProFormTextArea
            name="remark"
            label="审核备注"
            placeholder="请输入审核备注（可选）"
            fieldProps={{
              rows: 4,
            }}
          />
        </ProForm>
      </Modal>

      {/* 详情模态框 */}
      <Modal
        title="提交详情"
        open={detailModalVisible}
        onCancel={() => setDetailModalVisible(false)}
        footer={null}
        width={800}
      >
        {detailSubmission && (
          <div className="space-y-4">
            <div className="grid grid-cols-2 gap-4">
              <div>
                <label className="font-medium text-gray-700">网站名称：</label>
                <p className="mt-1">{detailSubmission.siteName}</p>
              </div>
              <div>
                <label className="font-medium text-gray-700">网站地址：</label>
                <p className="mt-1">
                  <a 
                    href={detailSubmission.siteUrl} 
                    target="_blank" 
                    rel="noopener noreferrer"
                    className="text-blue-500 hover:underline"
                  >
                    {detailSubmission.siteUrl}
                  </a>
                </p>
              </div>
              <div>
                <label className="font-medium text-gray-700">分类：</label>
                <p className="mt-1">{SubmissionCategoryMap[detailSubmission.category as keyof typeof SubmissionCategoryMap]}</p>
              </div>
              <div>
                <label className="font-medium text-gray-700">联系邮箱：</label>
                <p className="mt-1">{detailSubmission.email}</p>
              </div>
            </div>
            <div>
              <label className="font-medium text-gray-700">网站描述：</label>
              <p className="mt-1 p-3 bg-gray-50 rounded">{detailSubmission.description}</p>
            </div>
            {detailSubmission.tags && (
              <div>
                <label className="font-medium text-gray-700">标签：</label>
                <p className="mt-1">{detailSubmission.tags}</p>
              </div>
            )}
            <div className="grid grid-cols-2 gap-4">
              <div>
                <label className="font-medium text-gray-700">状态：</label>
                <p className="mt-1">
                  <Tag color={getStatusColor(detailSubmission.status)}>
                    {SubmissionStatusMap[detailSubmission.status as keyof typeof SubmissionStatusMap]}
                  </Tag>
                </p>
              </div>
              <div>
                <label className="font-medium text-gray-700">提交时间：</label>
                <p className="mt-1">{new Date(detailSubmission.createdAt).toLocaleString()}</p>
              </div>
            </div>
            {detailSubmission.remark && (
              <div>
                <label className="font-medium text-gray-700">审核备注：</label>
                <p className="mt-1 p-3 bg-gray-50 rounded">{detailSubmission.remark}</p>
              </div>
            )}
          </div>
        )}
      </Modal>
    </>
  );
};

export default SubmissionListPage;